package com.sx.micowell.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.example.mvvm.rx.RxBus;
import com.example.mvvm.until.LogUtils;
import com.example.mvvm.until.ToastUtils;
import com.sx.micowell.framework.app.AppConstant;
import com.sx.micowell.framework.tools.wxapi.WxEntryRespEvent;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * @Author: YY
 * @Time: 2021/9/11
 * @Describe TODO
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, AppConstant.WX_APP_ID);
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReq(BaseReq req) {
        LogUtils.e("onReq: " + req);
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
        LogUtils.d("onResp: "+resp);
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            LogUtils.d("onResp: 登录");
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    SendAuth.Resp authResp = (SendAuth.Resp) resp;
                    RxBus.getDefault().post(new WxEntryRespEvent(resp.getType(), resp.errCode, authResp.code, null));
                    ToastUtils.showShort("授权成功");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    ToastUtils.showShort("取消授权");
                    break;
                default:
                    ToastUtils.showShort("授权失败");
                    break;
            }
        }
        finish();
    }
}
